package com.yanqu.road.server.cmd.cross.activity;

import com.yanqu.road.pb.cross.activity.CrossActivityProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.ChatModule;
import com.yanqu.road.server.manger.player.WorldMessageMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;

import java.util.ArrayList;
import java.util.List;

@Cmd(code = Protocol.S_CROSS_ACTIVITY_CHAT_LIST_NOTIFY, desc = "跨服活动聊天列表通知")
public class CrossActivityChatListNotifyCmd extends AbstractCommand {
	private int activityId;
	private WorldMessageProto.WorldMessageListMsg chatListMsg;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		CrossActivityProto.CrossActivityChatListRespMsg reqMsg = CrossActivityProto.CrossActivityChatListRespMsg.parseFrom(packet.getBytes());
		activityId = reqMsg.getActivityId();
		chatListMsg = reqMsg.getDataList();
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		List<WorldMessageProto.WorldMessageTempMsg.Builder> forbiddenList = player.getModule(ChatModule.class).getCrossActivityForbiddenMsg(activityId);
		CrossActivityProto.CrossActivityChatListRespMsg.Builder respMsg = CrossActivityProto.CrossActivityChatListRespMsg.newBuilder();
		respMsg.setActivityId(activityId);
		List<WorldMessageProto.WorldMessageTempMsg.Builder> dataList = new ArrayList<>();
		if(null != forbiddenList){
			dataList.addAll(forbiddenList);
		}
		if(null != chatListMsg){
			for(WorldMessageProto.WorldMessageTempMsg tempMsg : chatListMsg.getDataListList()){
				dataList.add(tempMsg.toBuilder());
			}
		}
		dataList.sort((o1, o2) -> (int) (o1.getSendTime() - o2.getSendTime()));
		while (dataList.size() > WorldMessageMgr.MAX_MESSAGE_COUNT){
			dataList.remove(0);
		}
		WorldMessageProto.WorldMessageListMsg.Builder listMsg = WorldMessageProto.WorldMessageListMsg.newBuilder();
		for(WorldMessageProto.WorldMessageTempMsg.Builder msg : dataList){
			listMsg.addDataList(msg);
		}
		respMsg.setDataList(listMsg);
		player.sendPacket(Protocol.U_CROSS_ACTIVITY_CHAT_LIST, respMsg);
	}

	@Override
	public void sendData(GamePlayer player) {

	}

}
